package com.gcb.framework.security.custom;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * app登录验证 Provider
 * @author likai
 */
public class AppLoginAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    public AppLoginAuthenticationProvider(UserDetailsService userDetailsService){
        setUserDetailsService(userDetailsService);
    }

    /**
     * 重写authentication方法，实现app登录
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        AppLoginAuthenticationToken authenticationToken = (AppLoginAuthenticationToken) authentication;
        String userName = (String) authenticationToken.getPrincipal();
        //委托 UserDetailsService 查找系统用户
        UserDetails userDetails = userDetailsService.loadUserByUsername(userName);
        //鉴权成功,返回一个拥有鉴权的AbstractAuthenticationToken
        AppLoginAuthenticationToken appLoginAuthenticationToken = new AppLoginAuthenticationToken(userDetails, userDetails.getAuthorities());
        appLoginAuthenticationToken.setDetails(authenticationToken.getDetails());
        return appLoginAuthenticationToken;
    }

    /**
     * 重写supports方法，指定此AuthenticationProvider 仅支持短信验证码身份验证
     */
    @Override
    public boolean supports(Class<?> authentication){
        return AppLoginAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

}
